#import packages
from Basics.Detect_Shape import ShapeDetector
from Basics.Detect_Color import Colordetector
import argparse
import imutils
import cv2

#loading webcam
cap = cv2.VideoCapture(0)
while True:
	#load frames of image, resize it
	ret,image = cap.read()
	resized = imutils.resize(image, width=300)
	#ratio will be used to reset the coordinates from the resized one
	ratio = image.shape[0] / float(resized.shape[0])

	#initially process the image by blur gray threshhold cvt2LAB
	blurred = cv2.GaussianBlur(resized, (5,5), 0)
	gray = cv2.cvtColor(blurred, cv2.COLOR_BGR2GRAY)
	lab = cv2.cvtColor(blurred, cv2.COLOR_BGR2LAB)
	thresh = cv2.threshold(gray, 200, 255, cv2.THRESH_BINARY_INV)[1]
	# plan1 is 200 test good andif lower than 200 black  higher white INV is the opposite
	#cv2.imshow("midd1", lab)
	#cv2.waitKey(0)
	#cv2.imshow("midd2", thresh)
	#cv2.waitKey(0)
	#find contours
	cnts = cv2.findContours(thresh.copy(), 
						cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
	cnts = imutils.grab_contours(cnts)

	#initialize shape and color detector
	sd = ShapeDetector()
	cl = Colordetector()

	#loop & process the contours
	for c in cnts:
		#compute the center of the contour
		#not to put in the middle. print it. or it will crash because of 1/0.
		#M = cv2.moments(c)
		#cX = int(M["m10"] / M["m00"] * ratio)
		#cY = int(M["m01"] / M["m00"] * ratio)
	
		#detect the shape&color
		shape = sd.detect(c)
		color = cl.label(lab, c)
	
		#reset the coordinates using ratio & output results
		c = c.astype("float")
		c *= ratio 
		c = c.astype("int")
		text = "边长数:{} 颜色:{}".format(shape, color)
		cv2.drawContours(image, [c], -1, (0,255,0), 2)
		print (text)
		#cv2.putText(image, text, (cX,cY), 
					#cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,0), 1)
		cv2.imshow("Result", image)
	#reset image
	image = None
	
	if cv2.waitKey(1) == ord("q"):
			break
		#cv2.waitKey(0)
cap.release()
cv2.destroyAllWindows()
	
	#python3 Detect.py -i TEST1.png
	
